###
# Copyright © 2022 XXXXXXXXX
# @Author: zhangxiang
# @Date: 2022-07-19 09:42:07
 # @LastEditors: zhangxiang
 # @LastEditTime: 2023-11-24 10:33:00
# @Description:
#
###
while getopts ':b:p:c:' opt
do
    case $opt in
        b)
            BUILD_MODE=${OPTARG}
        ;;
        p)
            PUSH_MODE=${OPTARG}
        ;;
        c)
            CP_MODE=${OPTARG}
        ;;
        ?)
            echo "未知参数"
        ;;
        :)
            echo "没有输入任何参数 $OPTARG"
        ;;
    esac
done
BUILD_MODE=${BUILD_MODE:-package}
PUSH_MODE=${PUSH_MODE:-push}
CP_MODE=${CP_MODE:-not}
echo "BUILD_MODE is ${BUILD_MODE}"
echo "PUSH_MODE is ${PUSH_MODE}"
echo "CP_MODE is ${CP_MODE}"

NAME=172.17.4.80/public/cnp-fe
NAME_SIMPLE=cnp-fe
VERSION=$(git rev-parse --abbrev-ref HEAD)
# VERSION="CNP_M_V1.1"
DATE=$(date "+%m%d")
COMMIT_ID=$(git rev-parse --short HEAD)
TAG="${VERSION}-${DATE}-${COMMIT_ID}"
IMAGE_NAME="${NAME}:${TAG}"
SIMPLE_IMAGE_NAME="${NAME_SIMPLE}-${TAG}"
GREP_OUTPUT="$(docker images | grep "${TAG}")"
if [ -n "$GREP_OUTPUT" ] ; then
    echo "已有该镜像：${IMAGE_NAME}"
    exit 0
fi

# 打包
if [ $BUILD_MODE = 'package' ] ; then
    echo "开始执行 npm run build"
    npm run build
    echo "执行完成 npm run build"
    docker build -f ./docker/Dockerfile2 -t ${IMAGE_NAME} .
    elif [ $BUILD_MODE = 'local' ] ; then
    docker build -f ./docker/Dockerfile2 -t ${IMAGE_NAME} .
else
    docker build -f ./docker/Dockerfile -t ${IMAGE_NAME} .
fi
echo "镜像打包完成：${IMAGE_NAME}"

# 推送镜像
if [ $PUSH_MODE = 'push' ];
then
    docker push ${IMAGE_NAME}
    echo "镜像推送完成：${IMAGE_NAME}"
else
    echo "END, Do not need to push"
fi

# 拷贝到远程
if [ $CP_MODE = 'scp' ];
then
    BASE_SAVE_PATH="/home/zhangxiang/tars"  # 本地保存的镜像文件路径
    SAVE_IMAGE_NAME="${BASE_SAVE_PATH}/${SIMPLE_IMAGE_NAME}.tar" # 本地保存的镜像文件全名
    REMOTE_IP=root@172.171.11.101  # 远程服务器ip
    REMOTE_SAVE_PATH="/home/zhangxiang/tars" # 镜像文件在远程服务器上的路径
    docker save -o ${SAVE_IMAGE_NAME} ${IMAGE_NAME} # 保存本地镜像文件
    echo "保存镜像成功：${SAVE_IMAGE_NAME}"
    ## scp需要免密登录 打包服务器上执行 ssh-copy-id -i ~/.ssh/id_rsa.pub 172.171.11.101
    scp ${SAVE_IMAGE_NAME} ${REMOTE_IP}:${REMOTE_SAVE_PATH}
    echo "scp到远程服务器成功: (${REMOTE_IP}:${REMOTE_SAVE_PATH})"

    # ssh 远程执行命令
    ssh ${REMOTE_IP} "
        docker load -i ${REMOTE_SAVE_PATH}/${SIMPLE_IMAGE_NAME}.tar;
        echo '远程服务器Load镜像成功: (${REMOTE_IP}) load image ${IMAGE_NAME}';
        kubectl set image deployment/cnp-fe cnp-fe=${IMAGE_NAME}

        "
else
    echo "END, Do not need to scp"
fi